package com.efounder.chat.item;

import android.content.Context;
import android.graphics.Color;

import androidx.core.content.ContextCompat;

import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.item.manager.IMessageItem;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.frame.ViewSize;
import com.efounder.message.struct.IMStruct002;
import com.efounder.ui.util.DisplayUtil;
import com.efounder.util.AbFragmentManager;
import com.pansoft.xmlparse.FormatSet;
import com.pansoft.xmlparse.FormatTable;
import com.pansoft.xmlparse.MobileFormatUtil;

import org.json.JSONObject;

import java.util.Hashtable;
import java.util.Map;

/**
 * 点击可以跳转rn 原生以及webview的界面
 *
 * @author yqs
 * json模板示例
 * {
 * "title":"这是标题",
 * "subtitle":"这是副标题",
 * "image":"左侧大图",
 * "smallIcon":"小图",
 * "content":"内容",
 * "systemName":"系统名称",
 * "time":"2017-02-23"
 * "state":"已发送"
 * "urlstate":"online/offline"
 * "stateColor":"red"
 * "viewType":"webView"
 * "url":"www.baidu.com"
 * }
 */
public class CommonMessageItem extends LinearLayout implements IMessageItem {
    private TextView tvTitle;
    private TextView tvSubtitle;
    private TextView tvDetail;
    private ImageView ivIcon;
    private ImageView icSmallIcon;
    private TextView tvSystemname;
    private TextView tvTime;
    private TextView tvState;

    //    private ImageLoader imgLoader;
    private JSONObject jsonObject;
    private IMStruct002 message;
    private Context mContext;
    //判断是否分享名片
    private Boolean isCard = false;
    private AbFragmentManager abFragmentManager;

    public CommonMessageItem(Context context) {
        super(context);
        mContext = context;
//        imgLoader = ImageLoader.getInstance();
        abFragmentManager = new AbFragmentManager(context);
        LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflate.inflate(R.layout.wechatview_commonmessageitem_layout, this);//注意第二个参数
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvSubtitle = (TextView) findViewById(R.id.tv_subtitle);
        tvDetail = (TextView) findViewById(R.id.tv_detail);
        ivIcon = (ImageView) findViewById(R.id.iv_icon);
        icSmallIcon = (ImageView) findViewById(R.id.ic_smallIcon);
        tvSystemname = (TextView) findViewById(R.id.tv_systemname);
        tvTime = (TextView) findViewById(R.id.tv_time);
        tvState = (TextView) findViewById(R.id.tv_state);
        //param
        int width = DisplayUtil.getMobileWidth(context) * 2 / 3 - 20;
        LayoutParams lp = new LayoutParams(width, LayoutParams.MATCH_PARENT);
        this.setLayoutParams(lp);
        this.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String json = null;
                boolean isActivity = false;
                try {
                    //message.setExtMap(null);
                    json = new String(message.getBody(), "UTF-8");
                    net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(json);
                    Map<String, Object> map = jsonObject;

                    //默认的进入activity或者fragment的动画
                    int inTransition = R.anim.slide_in_from_right;
                    int outTransition = R.anim.slide_out_to_left;
                    if (jsonObject.has("tcms")) {
                        String tcms = jsonObject.getString("tcms");
                        if (!tcms.equals("") && tcms.equals("present")) {
                            //由下向上弹出
                            inTransition = R.anim.push_bottom_in;
                            outTransition = R.anim.push_top_out;
                        } else if (!tcms.equals("") && tcms.equals("alert")) {

                        }
                    }

                    StubObject stubObject = new StubObject();
                    Hashtable<String, Object> hashtable = new Hashtable<String, Object>();
                    stubObject.setStubTable(hashtable);
                    // Bundle bundle = new Bundle();
                    for (String key : map.keySet()) {
                        hashtable.put(key, map.get(key).toString());
                    }
                    //String AndroidShow =map.get("AndroidShow");//com.efounder.RNTaskDetailActivity"

                    hashtable.put("imStruct002", message);
                    if (jsonObject.has("AndroidShow")) {
                        String showClass = jsonObject.getString("AndroidShow");
                        if (showClass.equals("com.efounder.RNTaskDetailActivity")) {
                            //如果没有配置相应的类型，则弹框不跳转activity
                            FormatSet formatSet = MobileFormatUtil.getInstance().getFormatSet();
                            String djID = "";
                            net.sf.json.JSONObject taskData = jsonObject.getJSONObject("TaskData");
                            if (null != taskData) {
                                String PFLOW_ID = taskData.optString("PFLOW_ID");
                                if (PFLOW_ID != null && !PFLOW_ID.equals("")) {
                                    djID = PFLOW_ID;
                                } else {
                                    djID = taskData.optString("FLOW_ID");
                                }
                            }
                            if (null != djID && !djID.equals("")) {
                                FormatTable hfmt = formatSet.getFormatTableById(djID);

                                if (hfmt == null) {
                                    Toast.makeText(getContext(), "当前业务资源文件尚未配置，请联系管理员", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }

                        }
                    }
                    abFragmentManager.startActivity(stubObject, inTransition, outTransition);

//                    if (!isActivity) {
//                       // bundle.putString(CommonTransformFragmentActivity.EXTRA_TITLE_NAME, jsonObject.getString("title"));
//                        EFFrameUtils.startActivity(CommonTransformFragmentActivity.class, bundle, inTransition, outTransition);
//                    } else {
//                       // bundle.putString(EFTransformFragmentActivity.EXTRA_TITLE_NAME, jsonObject.getString("title"));
//                        Class activity = abFragmentManager.getActivity(stubObject);
//                        EFFrameUtils.startActivity(activity, bundle, inTransition, outTransition);
//
//                    }


//                    EFFrameUtils.pushFragment((Class<? extends BaseFragment>) fragment.getClass(),
//                            bundle, inTransition, outTransition);
                    // bundle.putString(EFTransformFragmentActivity.EXTRA_THEME, "dialog");com.efounder.chat.fragment.WebViewFragment
//                    EFFrameUtils.pushFragment((Class<? extends BaseFragment>) Class.forName(jsonObject.getString("AndroidShow")),
//                            bundle, inTransition, outTransition);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public View messageView() {
        return this;
    }

    @Override
    public ViewSize messageViewSize() {
        return null;
    }

    @Override
    public void setIMStruct002(IMStruct002 message) {
        this.message = message;
        try {
            String json = new String(message.getBody(), "UTF-8");
            jsonObject = new JSONObject(json);
            // FIXME: 2017/6/19 设置标题
            tvTitle.setText(jsonObject.getString("title"));
            tvTitle.setMaxLines(2);
            //// FIXME: 2017/6/19 设置副标题
            if (jsonObject.has("subtitle")) {
                tvSubtitle.setVisibility(View.VISIBLE);
                tvSubtitle.setText(jsonObject.getString("subtitle"));
                tvTitle.setSingleLine(true);
            } else {
                tvSubtitle.setVisibility(View.GONE);
            }
            //// FIXME: 2017/6/19 设置大图片
            if (jsonObject.has("systemName")) {
                String systemNameString = jsonObject.getString("systemName");
                isCard = systemNameString.equals("个人名片");
            }
            if (jsonObject.has("image")) {
                String imageString = jsonObject.getString("image");
                ivIcon.setVisibility(View.VISIBLE);
                if (imageString.equals("")) {
                    //在 ListView 和 RecyclerView 中的使用https://muyangmin.github.io/glide-docs-cn/doc/getting-started.html
                    Glide.with(mContext).clear(ivIcon);
                    if (isCard) {
                        ivIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.default_useravatar));
                    } else {
                        ivIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.unknow));
                    }
                } else {
                    if (isCard) {
                        LXGlideImageLoader.getInstance().displayRoundCornerImage(mContext, ivIcon, imageString, R.drawable.default_useravatar, R.drawable.default_useravatar, LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);
                    } else {
                        LXGlideImageLoader.getInstance().displayRoundCornerImage(mContext, ivIcon, imageString, R.drawable.unknow, R.drawable.unknow, LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);
                    }
                }
            } else {
                Glide.with(mContext).clear(ivIcon);
                if (isCard) {
                    ivIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.default_useravatar));
                } else {
                    ivIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.unknow));
                }
            }
            // FIXME: 2017/6/19 设置详情
            if (jsonObject.has("content")) {
                tvDetail.setText(jsonObject.getString("content"));
                tvDetail.setVisibility(View.VISIBLE);
            } else {
                tvDetail.setVisibility(View.GONE);
            }
            // FIXME: 2017/6/19 设置系统名称
            if (jsonObject.has("systemName")) {
                tvSystemname.setText(jsonObject.getString("systemName"));
                tvSystemname.setVisibility(View.VISIBLE);
            } else {
                tvSystemname.setVisibility(View.GONE);
            }
            // FIXME: 2017/6/19 设置左下角小图片
            if (jsonObject.has("smallIcon")) {
                String imageString = jsonObject.getString("smallIcon");
                if (imageString.equals("")) {
                    icSmallIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.wechat_icon_launcher));
                } else {
                    LXGlideImageLoader.getInstance().displayRoundCornerImage(mContext, icSmallIcon, imageString, R.drawable.unknow, R.drawable.unknow, LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);
                }
            } else {
                icSmallIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.wechat_icon_launcher));
            }
            // FIXME: 2017/6/19  设置时间
            if (jsonObject.has("time")) {
                String time = jsonObject.getString("time");
                if (!time.equals("")) {
                    tvTime.setVisibility(VISIBLE);
                    tvTime.setText(time);
                } else {
                    tvTime.setVisibility(GONE);
                }
            } else {
                tvTime.setVisibility(GONE);
            }
            // FIXME: 2017/6/19  设置状态
            if (jsonObject.has("state")) {
                String formState = jsonObject.getString("state");
                if (!formState.equals("")) {
                    tvState.setVisibility(VISIBLE);
                    tvState.setText(formState);
                } else {
                    tvState.setVisibility(INVISIBLE);
                }
            } else {
                tvState.setVisibility(INVISIBLE);
            }

            // FIXME: 2017/6/19  设置状态颜色
            if (jsonObject.has("stateColor")) {
                String stateLevel = jsonObject.getString("stateColor");
                if ("green".equals(stateLevel)) {//绿色
                    tvState.setBackgroundResource(R.drawable.form_textviewboard_green);
                    tvState.setTextColor(Color.parseColor("#4db239"));
                } else if ("blue".equals(stateLevel)) {//蓝色
                    tvState.setBackgroundResource(R.drawable.form_textviewboard_blue);
                    tvState.setTextColor(Color.parseColor("#108ee9"));
                } else if ("yellow".equals(stateLevel)) {//黄色
                    tvState.setBackgroundResource(R.drawable.form_textviewboard_yellow);
                    tvState.setTextColor(Color.parseColor("#fcaf0b"));
                } else if ("red".equals(stateLevel)) {//红色
                    tvState.setBackgroundResource(R.drawable.form_textviewboard_red);
                    tvState.setTextColor(Color.parseColor("#ff6666"));
                }
            } else {//默认
                //tvState.setBackgroundResource(R.drawable.form_textviewboard_red);
                tvState.setTextColor(ContextCompat.getColor(mContext, R.color.chat_red));
            }

            if (jsonObject.has("titleColor")) {
                String stateLevel = jsonObject.getString("titleColor");
                if ("green".equals(stateLevel)) {//绿色
                    tvTitle.setTextColor(Color.parseColor("#4db239"));
                } else if ("blue".equals(stateLevel)) {//蓝色
                    tvTitle.setTextColor(Color.parseColor("#108ee9"));
                } else if ("yellow".equals(stateLevel)) {//黄色
                    tvTitle.setTextColor(Color.parseColor("#fcaf0b"));
                } else if ("red".equals(stateLevel)) {//红色
                    tvTitle.setTextColor(Color.parseColor("#ff6666"));
                }
            } else {//默认
                tvTitle.setTextColor(mContext.getResources().getColor(R.color.common_item_text_title));
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean getIsInUse() {
        return this.isShown();
    }

    @Override
    public void setIsInUse(boolean isInUse) {


    }

    @Override
    public void prepareForReuse() {

    }
}
